/**
 * @author mars
 */

var timeout;
var sysMsgTimeOut;
var chat = {
	
	data : {
		columnH		: 420,
		contentBlock: 0,
		currentH	: 0,
		currentC	: 0,
		lastID		: 0,
		gid			: -1,
		first		: false,
		loading		: false,
		full		: false,
		selected	: ""
	},
	
	init : function(gid, title){
		chat.data.gid = gid;
		chat.data.first = true;
		chat.data.loading = true;
		chat.data.full = false;
		chat.data.contentBlock = $('#discussion');
		if(title!=undefined){
			var titleArea = chat.data.contentBlock.find('.galaxy-title .g-title-text');
			titleArea.text(title);
		}
		var emo_area = chat.data.contentBlock.find('.emotions-set-fun ul');
		var emo_btn = chat.data.contentBlock.find('.emotions');
		var sendie = chat.data.contentBlock.find('.sendie');
		if(!emo_area.children().length){
			for(var i = 1; i<=24; i++){
				var markup = chat.render('emoSet', i);
				emo_area.append(markup);
			};
			var emos = emo_area.find('li');
			emos.bind("click", function(){
				emo_area.parent().fadeOut('slow');
				emo_btn.removeClass("selected");
				var id = $(this).attr("id");
				sendie.val(sendie.val()+'['+id+']');
			});
		}
		
		(function getChatsTimeoutFunction(){
			if(!chat.data.full)
				chat.getChats(getChatsTimeoutFunction);
		})();
		
		chat.attachListener();
	},
	
	attachListener : function(){
		//input listeners
		var sendbtn = chat.data.contentBlock.find('.send-btn');
		var sendie = chat.data.contentBlock.find('.sendie');
		var send_msg_form = chat.data.contentBlock.find('.send-message-area');
		var next_page_btn = chat.data.contentBlock.find('.next-page');
		var sideBar = chat.data.contentBlock.find('.sideBarEle');
		var quit_galaxy_btn = chat.data.contentBlock.find('.quit-galaxy');
		var msgBox = chat.data.contentBlock.find('.infoMsg');
		var emo_btn = chat.data.contentBlock.find('.emotions');
		var bold_btn = chat.data.contentBlock.find('.boldFont');
		var italic_btn = chat.data.contentBlock.find('.italicFont');
		var emo_fun_set = chat.data.contentBlock.find('.emotions-set-fun');

		
		emo_btn.bind("click", 
		function(){
			if(!$(this).hasClass("selected")){
				emo_fun_set.fadeIn('slow');
				$(this).addClass("selected");
			}else{
				emo_fun_set.fadeOut('slow');
				$(this).removeClass("selected");
			}
		});
		
		
		
		bold_btn.bind("click", function(e){
			ModifySelection('bold', sendie[0]);
			return false;
		});
		
		italic_btn.bind("click", function(){
			ModifySelection('ita', sendie[0]);
			return false;
		});
		
		sendie.bind("keydown", function(e){
			if(e.ctrlKey && e.keyCode==13){
				send_msg_form.submit();
			}
		});
		
		sendie.bind("focus", function(){
			if(emo_fun_set.is(":visible")){
				emo_fun_set.fadeOut('slow');
				emo_btn.removeClass("selected");
			}
		});
		
		sendbtn.bind("click", function(){
			send_msg_form.submit();
		});
		
		send_msg_form.bind("submit", function(e){
			var text = sendie.val();
			if(text.length == 0){
				chat.sysMsg("You can't send an empty text.")
				return false;
			}
			sendie.val('');
			chat.submitChat(text);
			return false;
		});
		
		next_page_btn.bind("click", function(){

			$(this).fadeOut('fast');
			var right_column = chat.data.contentBlock.find('#chat-column2 ul');
			chat.data.lastID = right_column.find('li:last-child').attr('id').split("-")[1];
			chat.reinit();
			chat.data.loading = true;
			chat.data.full = false;
			(function getChatsTimeoutFunction(){
			if(!chat.data.full)
				chat.getChats(getChatsTimeoutFunction);
			})();
		});
		
		quit_galaxy_btn.show();
		quit_galaxy_btn.bind("click", function(){
			chat.quit(msgBox, function(){
				var Objects = $('#exGid_' + chat.data.gid);
				var joinObjects = Objects.find('.join-fun');
				joinObjects.html("[Join]");
				joinObjects.siblings('.join-layout').hide();
				joinObjects.show();
				var figureBlock = $('#mytopics-figure-block');
				$('#galaxy-'+chat.data.gid).fadeOut(function(){
					$(this).remove();
				});
				$('#branchGalaxy-'+chat.data.gid).fadeOut(function(){
					$(this).remove();
				});
				$('#branchGalaxyLine-'+chat.data.gid).fadeOut(function(){
					$(this).remove();
				});
				$('#galaxyLine-'+chat.data.gid).fadeOut(function(){
					$(this).remove();
				});
				chat.end();
			})
		});
		
		var pop_win = chat.data.contentBlock;
        var pop_mask = chat.data.contentBlock.find('#mask');
        var sideBar = chat.data.contentBlock.find('.sideBarEle');
        sideBar.removeClass('selected');
        collapseSideBar(pop_win);
		sideBar.bind("click", function() {
			if($(this).hasClass('selected')) {
				//collapse
				collapseSideBar(pop_win);
				popReloc($(window), pop_win, pop_mask);
				$(this).removeClass('selected');
			} else {
				//expand or change to another
				$(this).addClass('selected');
				var other = $(this).siblings();
				if(!other.hasClass('selected')) {
					//the other has not been selected, expand
					expandSideBar(pop_win);
					popReloc($(window), pop_win, pop_mask);
				} else {
					//the other has been selected, change.
					other.removeClass('selected');
				}
				if($(this).attr("id") == "expandUser-sideBar") {
					show_user_list();
				} else {
					show_chat_log();
				}
			}
		});
		

	},

	removeListener : function(){
		var sendbtn = chat.data.contentBlock.find('.send-btn');
		var sendie = chat.data.contentBlock.find('.sendie');
		var send_msg_form = chat.data.contentBlock.find('.send-message-area');
		var sideBar = chat.data.contentBlock.find('.sideBarEle');
		var quit_galaxy_btn = chat.data.contentBlock.find('.quit-galaxy');
		var emo_btn = chat.data.contentBlock.find('.emotions');
		var bold_btn = chat.data.contentBlock.find('.boldFont');
		var italic_btn = chat.data.contentBlock.find('.italicFont');
		var emo_fun_set = chat.data.contentBlock.find('.emotions-set-fun');
		
		emo_btn.unbind("click");
		bold_btn.unbind("click");
		italic_btn.unbind("click");
		sendie.unbind("keydown");
		sendie.unbind("focus");
		sendbtn.unbind("click");
		send_msg_form.unbind("submit");
		sideBar.unbind("click");
		quit_galaxy_btn.unbind("click");
		
	},

	submitChat : function(text){
		var d = new Date();
		var tempID = 't'+Math.round(Math.random()*1000000);
		var time = (1900+d.getYear())+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
		var temp_text = htmlEncode(text);
		var params = {
			'cid'		: 		tempID,
			'avatar'	: 		session_user_info['avatar'],
			'username'	: 		session_user_info['username'],
			'ts'		: 		time,
			'text'		: 		chat.textWrapper(temp_text)
		};
		chat.addChatLine(params);
		$.ziPOST('submitChat', {
			'gid' : chat.data.gid,
			'text' : text
		}, function(r) {
			var temp_e = chat.data.contentBlock.find('#chat-'+tempID);
			if(r['status']==1){
				temp_e.attr("id", 'chat-'+r['cid']);
			}else{
				temp_e.remove();
				chat.sysMsg("error. have you joined the galaxy?");
			}
		});


	},

	getChatLog	: function(callback){
		var dataBlock = chat.data.contentBlock.find('.right-column ul');
		$.ziGET('getChatsLog', {
			'gid' : chat.data.gid
		}, function(r) {
			if(r['gid']==chat.data.gid){
				dataBlock.html("");
				for(var i = 0; i < r['chats'].length; i++){
					var markup = chat.render('chatLog', r['chats'][i]);
					dataBlock.append(markup);
				}
			}
		});		
	},


	getChats : function(callback) {
		if(chat.data.loading)
			chat.data.contentBlock.find('.chat-wrap').append('<div style="margin: -250px 0 0 250px; float: left;" class="loading"><img src="img/loading.gif"/></div');

		if(chat.data.first){
			$.ziGET('getLatestChats', {
				'gid'	: chat.data.gid,
				'max_num': 15
			}, function(r){
				if(r['gid']==chat.data.gid){
					for(var i = 0; i< r.chats.length; i++){
						if(!chat.addChatLine(r['chats'][i]))
						break;
					}
					if(chat.data.loading){
						chat.data.contentBlock.find('.left-column .loading').remove();
						chat.data.loading = false;
					}
					chat.data.first = false;
					timeout = setTimeout(callback, 1000);
				}
			});
		}else{

			$.ziGET('getChats', {
				'lastID' : chat.data.lastID,
				'gid' : chat.data.gid,
				'max_num' : 15
			}, function(r) {
				if(r['gid'] == chat.data.gid && r['lastID'] == chat.data.lastID) {
					for(var i = 0; i < r.chats.length; i++) {
						if(!chat.addChatLine(r['chats'][i]))
							break;
					}
					if(chat.data.loading){
						chat.data.contentBlock.find('.left-column .loading').remove();
						chat.data.loading = false;
					}
					timeout = setTimeout(callback, 1000);
				}
			});


		}
	},

	getUsers : function(){
		var dataBlock = chat.data.contentBlock.find('.right-column ul');
		$.ziGET('galaxy_users', {
			'gid' : chat.data.gid
		}, function(r) {
			if(r['gid']==chat.data.gid){
				dataBlock.html("");
				for(var i = 0; i < r['data'].length; i++) {
					var markup = chat.render('chatUsers', r['data'][i]);
					var uid = r['data'][i]['uid'];
					dataBlock.append(markup);
					
					var userElement = dataBlock.find('#chatUsers-'+uid);
					var hoverElement = userElement.parent();
					hoverElement.mouseenter(function(){
						$(this).find('.userList-info').fadeIn('fast');
					});
					hoverElement.mouseleave(function(){
						$(this).find('.userList-info').fadeOut('fast');
					});
					
					var blockElement = userElement.find('.userList-info .block');
					var unblockElement = userElement.find('.userList-info .unblock');
					blockElement.click(function(){
						var id = $(this).parent().parent().attr("id");
						id = id.split("-")[1];
						chat.blockUsers(id);
					});
					
					unblockElement.click(function(){
						var id = $(this).parent().parent().attr("id");
						id = id.split("-")[1];
						chat.unblockUsers(id);
					});
				}
			}
		});


	},

	blockUsers : function(uid){
		chat.sysMsg('Blocking...');
		$.ziGET('blockUser', {
			'uid_to' : uid
		}, function(r) {
			chat.sysMsg('Success!');
			show_user_list();
		});

	},
	
	unblockUsers : function(uid){
		chat.sysMsg('Unblocking...');
		$.ziGET('unblockUser', {
			'uid_to' : uid
		}, function(r) {
			chat.sysMsg('Success!');
			show_user_list();
		});

	},

	circleUser : function(uid){
		chat.sysMsg('Requesting...');
		$.ziGET('circle', {
			'uid_to' : uid,
			'nid' : nebula_id
		}, function(r) {
			if(r == 1)
				chat.sysMsg('you have circled a friend');
			else
				chat.sysMsg('Something is wrong');
		});


	},
	
	uncircleUser : function(uid){
		chat.sysMsg('Requesting...');
		$.ziGET('uncircle', {
			'uid_to' : uid,
			'nid' : nebula_id
		}, function(r) {
			if(r == 1)
				chat.sysMsg('you have uncircled a friend');
			else
				chat.sysMsg('Something is wrong');
		});
	},

	addChatLine: function(params){
		var left_column = chat.data.contentBlock.find('#chat-column1 ul');
		var right_column = chat.data.contentBlock.find('#chat-column2 ul');
		var markup = chat.render('chatLine',params);
		var exists = chat.data.contentBlock.find('#chat-'+params['cid']);
		if(!exists.length){
			switch(chat.data.currentC){
				case 0:
					left_column.append(markup);
					var e = left_column.find('#chat-'+params['cid']);
					var eh = e.height();
					chat.data.currentH = chat.data.currentH+eh;
					if(chat.data.currentH>chat.data.columnH){
						//skip to next column
						e.remove();
						chat.data.currentC++;
						right_column.append(markup);
						chat.data.currentH = eh;
					}
					var insertedElement = chat.data.contentBlock.find('#chat-'+params['cid']);
					insertedElement.hide().fadeIn();
					chat.chatListenerWrapper(insertedElement, params);
					break;
				case 1:
					right_column.append(markup);
					var e = right_column.find('#chat-'+params['cid']);
					var eh = e.height();
					chat.data.currentH = chat.data.currentH+eh;
					if(chat.data.currentH>chat.data.columnH){
						//skip to next column
						e.remove();
						chat.data.currentC++;
						chat.data.currentH = 0;
						chat.data.full = true;
						var next_btn = chat.data.contentBlock.find('.next-page').fadeIn('slow');
						return false;
					}
					var insertedElement = chat.data.contentBlock.find('#chat-'+params['cid']);
					insertedElement.hide().fadeIn();
					chat.chatListenerWrapper(insertedElement, params);
					break;
				default:
			}
		}
		return true;
	},
	
	chatListenerWrapper : function(element, params){
		var sendie = chat.data.contentBlock.find('.sendie');
		var quote_btn = element.find('.quote');
		quote_btn.bind("click", function(){
			var t = $(this).siblings('.chat-text').html();
			var temp = $('<div/>').html(t);
			var quoted = temp.find('.chat-quote');
			quoted.remove();
			t = temp.text();
			sendie.val(sendie.val()+'[quote]'+t+'[/quote]');
		});
		var chat_avatar = element.find('.chat-avatar');
		var x = chat_avatar.position().left;
		var y = chat_avatar.position().top;
		var avatar_pic = chat_avatar.find('img');
		reSizeAvatar(avatar_pic);
		params = {
			'x' : x,
			'y' : y,
			'id': params['cid'],
			'avatar': params['avatar'],
			'username': params['username'],
			'uid'	: params['uid']
		};
		var markup = chat.render('namecard', params);
		var namecard = $(markup).appendTo(chat.data.contentBlock.find('.galaxy-container'));
		var namecard_avatar = namecard.find('img');
		reSizeAvatar(namecard_avatar);
		var tout = undefined;
		var toout = undefined;
		chat_avatar.mouseenter(function(){
			if(tout==undefined){
				tout = setTimeout(function(){
					namecard.css("margin-top", "-120px");
					var innercard = namecard.find('.inner-card');
					var htmlData = innercard.html();
					innercard.html('<div style="margin: 38px 0 38px 0;"><img src="img/loading.gif"/></div>');
					namecard.fadeIn('fast');
					$.ziGET('galaxies_namecard', {
						'uid' : params['uid'],
						'nid' : nebula_id
					}, function(r){
						innercard.html(htmlData);
						var nebulaBlock = namecard.find('.name-card-nebula ul');
						nebulaBlock.html("");
						for(var i=0; i<r['data'].length; i++){
							nebulaBlock.append("<li><img src="+r['data'][i]['icon']+"></li>");
						}
						
						var profvArea = namecard.find('.status');
						var profv_list = r['profv']['prof_vector'];
						var profv = profv_list.split(" ");
						profvArea.html('Prof: '+profv[nebula_id]);
						var opArea = namecard.find('a[name=circle-fun]');
						if(r['circled']){

							opArea.html('uncircle');
							var circle_btn = namecard.find('a[name=circle-fun]');
							circle_btn.click(function(e) {
								e.preventDefault();
								var uid = $(this).attr("href");
								chat.uncircleUser(uid);
							});


						}else{
														
							opArea.html('circle');
							var circle_btn = namecard.find('a[name=circle-fun]');
							circle_btn.click(function(e) {
								e.preventDefault();
								var uid = $(this).attr("href");
								chat.circleUser(uid);
							});
						}
						var namecardH = namecard.height();
						namecard.css("margin-top", '-'+namecardH+'px');
					});
				}, 500);
			}
		});
		namecard.mouseenter(function(){
			if(toout!=undefined){
				clearTimeout(toout);
				toout = undefined;
			}
		});
		chat_avatar.mouseleave(function(){
			if(toout==undefined){
				toout = setTimeout(function(){
					namecard.fadeOut('fast');
					clearTimeout(tout);
					tout = undefined;
					toout = undefined;
				}, 100);
			}
		});
		namecard.mouseleave(function(){
			namecard.fadeOut('fast');
		});
		
	},
	
	textWrapper : function(text){
		var r = text;
		r = r.replace('[bold]', '<span style="font-weight: bold">');
		r = r.replace('[/bold]', '</span>');
		r = r.replace('[ita]', '<span style="font-weight: bold; font-style: italic;">');
		r = r.replace('[/ita]', '</span>');
		r = r.replace('[quote]', '<div class="chat-quote roundedS"><span style="font-size: 10px;">quoted</span><hr>');
		r = r.replace('[/quote]', '</div>')
		var reg = new RegExp("\\[emo\-[0-9]+\]", "g");
		var reg2 = new RegExp("[0-9]+", "g");
		var tags = r.match(reg);

		if(tags != null) {
			for(var i = 0; i < tags.length; i++) {
				var id = tags[i].match(reg2);
				if(id!= null)
					r = r.replace(tags[i], '<span style="vertical-align: -5px; margin-right: 2px; display: inline-block;"><img src="img/emos/emotions_' + id + '.png"/></span>');
			}
		}

		return r;
	},
	
	render : function(template, params){
		var arr = [];
		switch(template){
			case 'chatLine':
				params['text'] = chat.textWrapper(params['text']);
				arr = [
					'<li id="chat-',params['cid'],'"><div style="float: left; overflow: hidden;"><div class="chat-avatar avatar-area"><img style="display:none;" src="',params['avatar'],'"/></div></div>',
					'<div class="chat-tri"></div><div class="chat-authorText-wrap roundedS shadow">',
					'<div class="chat-author">',params['username'],' @ ',render_chat_timestamp(params['ts'], undefined),'</div>',
					'<hr><div class="chat-text">',params['text'],'</div>',
					'<div class="quote" style="float: right; cursor: pointer;">',
					'<span style="display: inline-block; vertical-align: -5px;">',
					'<img src="img/tag.png"/></span><span style="font-size: 10px;"> Quote</span>',
					'</div></div></li>'
				];
				break;
			case 'chatUsers':
				arr = [
					'<li><div id="chatUsers-',params['uid'],'" class="userList-element ',(params['online']==1)?"":"offline",'"><div class="userList-avatar"><a href="./circlefile.php?uid=',params['uid'],'" target="_blank"><img style="width:22px;height:22px;" src="',params['avatar'],'"/></a></div>',
					'<div class="userList-name">',params['username'],'</div>',
					'<div class="userList-info"><div class="block" style="',(params['blocked']==1)?'display: none;':'','">block</div><div class="unblock" style="',(params['blocked']==1)?'':'display: none;','">unblock</div></div></div></li>'
				];
				break;
			case 'chatLog':
				arr = [
					'<li><div class="chat-log-element"><div class="chat-log-author">',params['username'],' @ ',params['ts'],'</div>',
					'<div class="chat-log-text">',params['text'],'</div></div></li>'
				];
				break;
			case 'emoSet':
				arr = [
					'<li id="emo-',params<10?'0'+params:params,'" class="emo-element"><img src="img/emos/emotions_',params<10?'0'+params:params,'.png"/></li>'
				];
				break;
			case 'namecard':
				arr = [
					'<div id="namecard-',params['id'],'" class="name-card" style="left:',
					params['x'],'px;top:',params['y'],'px;"><div class="inner-card shadow">',
					'<div style="overflow: auto;"><div class="avatar-column"><div class="name-avatar">',
					'<img src="',params['avatar'],
					'"/></div>',
					'</div><div class="info-column"><ul><li class="name-username" title="',params['username'],'">',params['username'],
					'</li><li style="font-size: 10px; margin: 2px 0;">Male</li><li class="status"></li></ul></div></div><div class="name-card-nebula">',
					'<ul></ul></div><div class="name-card-op"><a name="circle-fun" href="',params['uid'],'">Circle</a></div></div>',
					'<div class="inner-tri"></div></div>',
				];
		}
		
		
		return arr.join('');
	},
	
	quit:function(msgBox, callback){
		chat.sysMsg("Quitting");
		$.ziGET('quit_galaxy', {
			'gid' : chat.data.gid
		}, function(r) {
			chat.sysMsg("Quitted");
			setTimeout(callback, 600);
		});


	},
	
	sysMsg:function(msg){
		if(sysMsgTimeOut!=undefined)
			clearTimeout(sysMsgTimeOut);
		var msgBox = chat.data.contentBlock.find('.infoMsg');
		var msgWindow = chat.data.contentBlock;
		msgBox.html(msg);
		var winH = msgWindow.height();
    	var winW = msgWindow.width();
    
    	//Set the popup window to center
    	msgBox.css('top', winH / 2 - msgBox.height());
    	msgBox.css('left', winW / 2 - msgBox.width());
    	msgBox.fadeIn('slow', function(){
    		sysMsgTimeOut = setTimeout(function(){
    			msgBox.hide();
    			clearTimeout(sysMsgTimeOut);
    		}, 500);
    	});
	},
	
	
	toolEnd : function(){
		var emo_fun_set = chat.data.contentBlock.find('.emotions-set-fun');
		
		//hide emo_fun_set
		emo_fun_set.hide();
	},
	
	
	reinit : function(){
		var left_column = chat.data.contentBlock.find('#chat-column1 ul');
		var right_column = chat.data.contentBlock.find('#chat-column2 ul');
		chat.data.currentC = 0;
		chat.data.currentH = 0;
		left_column.html("");
		right_column.html("");
		chat.data.contentBlock.find('.next-page').hide();
		chat.data.contentBlock.find('.name-card').remove();
	},
	
	end : function(){
		chat.removeListener();
		chat.reinit();
		chat.data.gid = -1;
		chat.data.lastID = 0;
		clearTimeout(timeout);
		$('#mask').hide();
		$('.window').fadeOut('fast');
		chat.toolEnd();
	}
}

function collapseSideBar(contentBlock){
	var right_col = contentBlock.find('.right-column');
	var elements = right_col.find('ul');
	elements.hide();
	right_col.css("border-left", "0");
	contentBlock.css("width", "620px");
	right_col.find('.sideBar').css("right", "125px");

}

function expandSideBar(contentBlock){
	var right_col = contentBlock.find('.right-column');
	var elements = right_col.find('ul');
	elements.show();
	right_col.css("border-left", "1px solid #D0D0D0");
	contentBlock.css("width", "800px");
	right_col.find('.sideBar').css("right", "-55px");
}


function show_user_list(){
	var dataBlock = chat.data.contentBlock.find('.right-column ul');
	dataBlock.html('<div style="margin: 220px 0 0 30px;" class="loading"><img src="img/loading.gif"/></div>');
	chat.getUsers();
}


function show_chat_log(){
	var dataBlock = chat.data.contentBlock.find('.right-column ul');
	dataBlock.html('<div style="margin: 220px 0 0 30px;" class="loading"><img src="img/loading.gif"/></div>');
	chat.getChatLog();
}

function ModifySelection(template, textarea) {
	var s = '['+template+']';
	var e = '[/'+template+']';
	if('selectionStart' in textarea) {
		// check whether some text is selected in the textarea
		if(textarea.selectionStart != textarea.selectionEnd) {
			
			var newText = textarea.value.substring(0, textarea.selectionStart) + s + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd) + e + textarea.value.substring(textarea.selectionEnd);
			textarea.value = newText;
		}
	} else {// Internet Explorer before version 9
		// create a range from the current selection
		var textRange = document.selection.createRange();
		// check whether the selection is within the textarea
		var rangeParent = textRange.parentElement();
		if(rangeParent === textarea) {
			textRange.text = s + textRange.text + e;
		}
	}
}
